from django.contrib.auth import authenticate
from django.utils import timezone
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from user_management.models import CustomUser, LoginHistory
from .models import UserLoginAttempt
import json
import os
from PIL import Image
import uuid


def get_client_ip(request):
    """获取客户端IP地址"""
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
    """用户登录"""
    username = request.data.get('username')
    password = request.data.get('password')

    if not username or not password:
        return Response({
            'error': '用户名和密码不能为空'
        }, status=status.HTTP_400_BAD_REQUEST)

    # 获取客户端信息
    ip_address = get_client_ip(request)
    user_agent = request.META.get('HTTP_USER_AGENT', '')

    # 记录登录尝试
    login_attempt = UserLoginAttempt.objects.create(
        username=username,
        ip_address=ip_address,
        user_agent=user_agent,
        is_success=False
    )

    # 验证用户
    user = authenticate(username=username, password=password)

    if user is not None:
        if user.is_active:
            # 登录成功
            login_attempt.is_success = True
            login_attempt.save()

            # 更新用户登录信息
            user.last_login_ip = ip_address
            user.login_count += 1
            user.last_login = timezone.now()
            user.save()

            # 记录登录历史
            LoginHistory.objects.create(
                user=user,
                ip_address=ip_address,
                user_agent=user_agent,
                is_success=True
            )

            # 生成JWT令牌
            refresh = RefreshToken.for_user(user)

            return Response({
                'message': '登录成功',
                'user': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'first_name': user.first_name,
                    'last_name': user.last_name,
                    'is_superuser': user.is_superuser,
                    'is_staff': user.is_staff,
                    'is_active': user.is_active,
                },
                'tokens': {
                    'refresh': str(refresh),
                    'access': str(refresh.access_token),
                }
            })
        else:
            login_attempt.failure_reason = '用户账户已被禁用'
            login_attempt.save()
            return Response({
                'error': '用户账户已被禁用'
            }, status=status.HTTP_401_UNAUTHORIZED)
    else:
        # 用户不存在或密码错误
        login_attempt.failure_reason = '用户名或密码错误'
        login_attempt.save()
        return Response({
            'error': '用户名或密码错误'
        }, status=status.HTTP_401_UNAUTHORIZED)


@api_view(['POST'])
@permission_classes([AllowAny])
def register(request):
    """用户注册"""
    username = request.data.get('username')
    password = request.data.get('password')
    email = request.data.get('email')
    first_name = request.data.get('first_name', '')
    last_name = request.data.get('last_name', '')

    # 验证必填字段
    if not username or not password:
        return Response({
            'error': '用户名和密码不能为空'
        }, status=status.HTTP_400_BAD_REQUEST)

    # 检查用户名是否已存在
    if CustomUser.objects.filter(username=username).exists():
        return Response({
            'error': '用户名已存在'
        }, status=status.HTTP_400_BAD_REQUEST)

    # 检查邮箱是否已存在
    if email and CustomUser.objects.filter(email=email).exists():
        return Response({
            'error': '邮箱已被使用'
        }, status=status.HTTP_400_BAD_REQUEST)

    try:
        # 创建新用户
        user = CustomUser.objects.create_user(
            username=username,
            password=password,
            email=email or f"{username}@example.com",
            first_name=first_name,
            last_name=last_name
        )

        # 获取客户端信息
        ip_address = request.META.get('HTTP_X_FORWARDED_FOR',
                                    request.META.get('REMOTE_ADDR', ''))
        user_agent = request.META.get('HTTP_USER_AGENT', '')

        # 记录注册历史
        LoginHistory.objects.create(
            user=user,
            ip_address=ip_address,
            user_agent=user_agent,
            is_success=True
        )

        return Response({
            'message': '注册成功',
            'user': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'first_name': user.first_name,
                'last_name': user.last_name,
            }
        }, status=status.HTTP_201_CREATED)

    except Exception as e:
        return Response({
            'error': f'注册失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
def logout(request):
    """用户登出"""
    try:
        refresh_token = request.data.get('refresh_token')
        if refresh_token:
            token = RefreshToken(refresh_token)
            token.blacklist()
        return Response({'message': '登出成功'})
    except Exception as e:
        return Response({'error': '登出失败'}, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
def user_suggestions(request):
    """获取用户名建议（基于登录历史）"""
    # 获取最近登录的用户名
    recent_users = LoginHistory.objects.filter(
        is_success=True
    ).values_list('user__username', flat=True).distinct()[:10]

    return Response({
        'suggestions': list(recent_users)
    })


@api_view(['GET', 'PUT'])
def user_profile(request):
    """获取或更新用户信息"""
    user = request.user

    if request.method == 'GET':
        # 解析背景设置
        background_settings = {}
        try:
            if user.background_settings:
                background_settings = json.loads(user.background_settings)
        except:
            background_settings = {'type': 'none'}

        return Response({
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'first_name': user.first_name,
            'last_name': user.last_name,
            'full_name': user.full_name,  # 添加 full_name 字段
            'phone': user.phone,

            'bio': getattr(user, 'bio', ''),
            'avatar': user.avatar.url if user.avatar else None,
            'background_image': user.background_image.url if user.background_image else None,
            'background_settings': background_settings,
            'login_count': user.login_count,
            'last_login': user.last_login,
            'last_login_ip': user.last_login_ip,
            'date_joined': user.date_joined,
            'is_superuser': user.is_superuser,
            'is_staff': user.is_staff,
            'is_active': user.is_active,
        })

    elif request.method == 'PUT':
        # 更新用户信息
        data = request.data

        # 根据用户权限确定可编辑字段
        if user.is_superuser:
            # 超级管理员可以编辑除用户名外的所有字段
            allowed_fields = ['email', 'full_name', 'first_name', 'phone', 'bio']
        elif user.is_staff:
            # 普通管理员可以编辑部分字段
            allowed_fields = ['email', 'full_name', 'first_name', 'phone', 'bio']
        else:
            # 普通用户只能编辑个人简介
            allowed_fields = ['bio']

        updated_fields = {}
        for field in allowed_fields:
            if field in data:
                if field == 'full_name':
                    # 同时更新 full_name 和 first_name 字段，保持数据一致性
                    setattr(user, 'full_name', data[field])
                    setattr(user, 'first_name', data[field])
                    setattr(user, 'last_name', '')  # 清空 last_name
                    updated_fields[field] = data[field]
                elif field == 'first_name':
                    # 如果直接更新 first_name，也同时更新 full_name
                    setattr(user, 'first_name', data[field])
                    setattr(user, 'full_name', data[field])
                    setattr(user, 'last_name', '')  # 清空 last_name
                    updated_fields[field] = data[field]
                else:
                    setattr(user, field, data[field])
                    updated_fields[field] = data[field]

        if not updated_fields:
            return Response({
                'error': '没有可更新的字段'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            user.save()

            # 根据用户类型返回不同的消息
            if user.is_superuser:
                message = '个人信息更新成功'
            else:
                message = '个人资料更新成功'

            return Response({
                'message': message,
                'updated_fields': updated_fields,
                'user_permissions': {
                    'is_superuser': user.is_superuser,
                    'is_staff': user.is_staff,
                    'allowed_fields': allowed_fields
                },
                'user': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'full_name': user.full_name,
                    'phone': user.phone,
                    'bio': getattr(user, 'bio', ''),
                    'avatar': user.avatar.url if user.avatar else None,
                }
            })
        except Exception as e:
            return Response({
                'error': f'更新失败: {str(e)}'
            }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def change_password(request):
    """修改密码"""
    user = request.user
    old_password = request.data.get('old_password')
    new_password = request.data.get('new_password')

    if not old_password or not new_password:
        return Response({
            'error': '旧密码和新密码不能为空'
        }, status=status.HTTP_400_BAD_REQUEST)

    # 验证旧密码
    if not user.check_password(old_password):
        return Response({
            'error': '当前密码不正确'
        }, status=status.HTTP_400_BAD_REQUEST)

    # 设置新密码
    user.set_password(new_password)
    user.save()

    return Response({
        'message': '密码修改成功'
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def upload_avatar(request):
    """上传头像"""
    if 'file' not in request.FILES:
        return Response({
            'error': '请选择要上传的文件'
        }, status=status.HTTP_400_BAD_REQUEST)

    file = request.FILES['file']

    # 验证文件类型
    allowed_types = ['image/jpeg', 'image/png', 'image/gif']
    if file.content_type not in allowed_types:
        return Response({
            'error': '只支持 JPG、PNG、GIF 格式的图片'
        }, status=status.HTTP_400_BAD_REQUEST)

    # 验证文件大小 (2MB)
    if file.size > 2 * 1024 * 1024:
        return Response({
            'error': '文件大小不能超过 2MB'
        }, status=status.HTTP_400_BAD_REQUEST)

    try:
        # 生成唯一文件名
        ext = os.path.splitext(file.name)[1]
        filename = f"{request.user.id}_{uuid.uuid4().hex}{ext}"

        # 处理图片 - 调整大小
        image = Image.open(file)

        # 转换为RGB模式（处理RGBA图片）
        if image.mode in ('RGBA', 'LA', 'P'):
            background = Image.new('RGB', image.size, (255, 255, 255))
            if image.mode == 'P':
                image = image.convert('RGBA')
            background.paste(image, mask=image.split()[-1] if image.mode == 'RGBA' else None)
            image = background

        # 调整图片大小为 200x200
        image = image.resize((200, 200), Image.Resampling.LANCZOS)

        # 保存处理后的图片
        from io import BytesIO
        output = BytesIO()
        image.save(output, format='JPEG', quality=85)
        output.seek(0)

        # 删除旧头像
        if request.user.avatar:
            try:
                default_storage.delete(request.user.avatar.name)
            except:
                pass

        # 保存新头像
        request.user.avatar.save(
            filename,
            ContentFile(output.read()),
            save=True
        )

        return Response({
            'message': '头像上传成功',
            'avatar_url': request.user.avatar.url
        })

    except Exception as e:
        return Response({
            'error': f'头像上传失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def upload_background(request):
    """上传用户背景图片"""
    try:
        if 'background' not in request.FILES:
            return Response({
                'error': '请选择背景图片文件'
            }, status=status.HTTP_400_BAD_REQUEST)

        background_file = request.FILES['background']

        # 验证文件类型
        if not background_file.content_type.startswith('image/'):
            return Response({
                'error': '只支持图片文件'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 验证文件大小 (最大2MB)
        if background_file.size > 2 * 1024 * 1024:
            return Response({
                'error': '图片大小不能超过2MB'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 验证图片格式
        try:
            img = Image.open(background_file)
            img.verify()
        except Exception:
            return Response({
                'error': '图片文件格式不正确'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 重新打开图片进行处理
        background_file.seek(0)
        img = Image.open(background_file)

        # 转换为RGB模式（如果需要）
        if img.mode in ('RGBA', 'LA', 'P'):
            img = img.convert('RGB')

        # 调整图片尺寸（建议尺寸400x200）
        target_width, target_height = 400, 200
        img.thumbnail((target_width, target_height), Image.Resampling.LANCZOS)

        # 保存处理后的图片
        from io import BytesIO
        output = BytesIO()
        img.save(output, format='JPEG', quality=85, optimize=True)
        output.seek(0)

        # 生成唯一文件名
        file_name = f"background_{request.user.id}_{uuid.uuid4().hex[:8]}.jpg"

        # 删除旧的背景图片
        if request.user.background_image:
            try:
                default_storage.delete(request.user.background_image.name)
            except:
                pass

        # 保存新的背景图片
        request.user.background_image.save(
            file_name,
            ContentFile(output.read()),
            save=True
        )

        return Response({
            'message': '背景图片上传成功',
            'background_url': request.user.background_image.url
        })

    except Exception as e:
        return Response({
            'error': f'背景图片上传失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def update_background_settings(request):
    """更新用户背景设置"""
    try:
        user = request.user
        settings_data = request.data

        # 验证设置数据
        background_type = settings_data.get('type', 'none')
        if background_type not in ['none', 'preset', 'custom']:
            return Response({
                'error': '无效的背景类型'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 构建设置对象
        background_settings = {
            'type': background_type,
            'preset_id': settings_data.get('preset_id', ''),
            'opacity': min(max(float(settings_data.get('opacity', 0.8)), 0.1), 1.0),
            'position': settings_data.get('position', 'center')
        }

        # 保存设置
        user.background_settings = json.dumps(background_settings)
        user.save()

        return Response({
            'message': '背景设置更新成功',
            'settings': background_settings
        })

    except Exception as e:
        return Response({
            'error': f'背景设置更新失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
